/*
 * util.js
 * 工具类
 */
import axios from "axios"
import qs from "qs"
import APP from "./appConfig"
import { Indicator } from 'mint-ui';
const baseParam = {
 
}
const uleUrl=APP.DOMAIN
/* 一些请求的全局配置 */
axios.defaults.baseURL = APP.DOMAIN;
//axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.timeout = 8000;
/* GET请求 */
function GET(url, params) {
  url = url + fiterParams(params);
  return axios.get(url, params).then(reqResult).catch(reqErr);
}
/* POST请求 */
function POST(url, params, hasLoad = true, contentType = 'application/json') {
  if (hasLoad)
  return axios.post(url, { ...baseParam, ...params }, { headers: { 'Content-Type': contentType } }).then(reqResult).catch(reqErr);;
}
function fiterParams(params) {
  let urlmix = '';
  if (params) {
    let paramstr = '';
    if (typeof params === 'string') urlmix = '/' + params;
    if (typeof params === 'object') {
      paramstr = qs.stringify(params);
      urlmix = '?' + paramstr;
    }
  }
  return urlmix;
}
function JSONP(url, params, hasLoad = true) {
  Indicator.open({
    text: '正在加载...',
    spinnerType: 'fading-circle',//'snake''fading-circle''double-bounce''triple-bounce'
  });
   return $.ajax({
    url: uleUrl+url, 
    type: "get",
    dataType: "jsonp",
    data:{...params},
    jsonp: "jsoncallback",
  }).then((res)=>{
    Indicator.close();
    return res
  }).catch((err)=>{
    Indicator.close();
    return err
  })
}
function JsonpPost(url, params, hasLoad = true) {
  let contentType = 'application/json'
  
  return $.ajax({
   url: uleUrl+url, 
   type: "post",
   data:{...params},
   headers: { 'Content-Type': contentType },
 }).then((res)=>{
   return res
 }).catch((err)=>{
   return err
 })
}
function reqResult(res) {
  let data = null;
  if (res.status === 200) {//&& res.statusText. toLowerCase() == 'ok'
    //console.log('req res', res.data);
    if (res.data && res.data.code)
      data = res.data.data;
    else { throw { code: res.data.code, msg: res.data.msg } }
  } else { throw 'Request failed, ' + JSON.stringify(res); }
  return data;
}
function reqErr(e) {
  console.error('Request error:', e);
  if (e && e.message && e.message.toLowerCase().indexOf('timeout') > -1)
    e = { code: 0, msg: '请求超时,请稍候再试' }
  throw e;
}
export { APP, JSONP, GET, POST,JsonpPost }
